#include <cstring>
#include <string>
#include <iostream>

#include <unistd.h>
#include <fcntl.h>

#include <iomux/iomuxhelper.hpp>

class DemoHelper {
public:
    DemoHelper(int files_num): m_files_num(files_num) {}

    ~DemoHelper() {
        remove_files();
    }

    int create_files(void);
    int remove_files(void);

    std::vector<FileDesc *> get_files(void) const {
        return m_files;
    }
private:
    int m_files_num = 0;
    std::vector<FileDesc *>m_files;
};

int DemoHelper::create_files(void)
{
    for (int i = 0; i < m_files_num; i++) {
        char name[128];
        sprintf(name, "fifo%d", i);
        mkfifo(name, 0644);

        MyFifo *f = new MyFifo(name);

        std::cout << name << ": " << f->get_fd() << std::endl;
        // ph->add_file(static_cast<FileDesc *>(f), POLLIN);
        f->set_nonblock(true);
        m_files.push_back(f);
    }

    return 0;
}

int DemoHelper::remove_files(void)
{
    // 并发问题？
    for (auto &it: m_files) {
        close(it->get_fd());
        delete it;
        it = nullptr;
    }

    m_files.clear();

    for (int i = 0; i < m_files_num; i++) {
        char name[128];
        sprintf(name, "fifo%d", i);
        unlink(name);
    }

    return 0;
}
